package com.example.springbootServiceNetwork.demos.web.WebSocket;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.springbootServiceNetwork.demos.web.Config.SparkApiConfig;
import com.example.springbootServiceNetwork.demos.web.Dto.SparkParamDto;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.example.springbootServiceNetwork.demos.web.Tool.SparkUtil.getAuthUrl;
import static com.example.springbootServiceNetwork.demos.web.Tool.SparkUtil.getSparkJsonSocket;


/**
 * websocket操作类
 */
@Component
@ServerEndpoint("/websocket/{userId}")
public class WebSocketServer {

    /**
     * 日志工具
     */
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 用户id
     */
    private String userId;
    /**
     * 用来存放每个客户端对应的MyWebSocket对象
     */
    private static final CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();
    /**
     * 用来存在线连接用户信息
     */
    private static final ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();


    /**
     * 链接成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        try {
            this.session = session;
            this.userId = userId;
            webSockets.add(this);
            sessionPool.put(userId, session);
            logger.info("【websocket消息】有新的连接，总数为:" + webSockets.size());
        } catch (Exception ignored) {
        }
    }

    /**
     * 链接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        try {
            webSockets.remove(this);
            sessionPool.remove(this.userId);
            logger.info("【websocket消息】连接断开，总数为:" + webSockets.size());
        } catch (Exception ignored) {
        }
    }

    /**
     * 收到客户端消息后调用的方法
     */
    @OnMessage
    public void onMessage(String message) {
        SparkParamDto sparkParam = JSON.parseObject(message, SparkParamDto.class);
        if (Objects.equals(sparkParam.getType(), "spark")){
            getSparkApiChat(sparkParam);
        }
    }

    /**
     * 发送错误时的处理
     *  session
     *  error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("用户错误,原因:" + error.getMessage());
        error.fillInStackTrace();
    }

    /**
     * 此为广播消息
     * 向每个用户都推送消息
     */
    public void sendAllMessage(String message) {
//        logger.info("【websocket消息】广播消息:" + message);
//        System.out.println(sessionPool);
        for (WebSocketServer webSocket : webSockets) {
            try {
                if (webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.fillInStackTrace();
            }
        }
    }


    /**
     * 此为广播消息
     * 向指定用户推送消息
     */
    public boolean sendMessageToUser(String userId, String message) {
        //logger.info("【websocket消息】向用户" + userId + "发送消息：" + message);
        AtomicBoolean pass= new AtomicBoolean(false);
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            try {
                pass.set(true);
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.fillInStackTrace();
            }
        }
        return pass.get();
    }


    /**
     * 此为单点消息
     */
    public void sendOneMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            try {
//                logger.info("【websocket消息】 单点消息:" + message);
                session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.fillInStackTrace();
            }
        }
    }

    /**
     * 此为单点消息(多人)
     */
    public void sendMoreMessage(String[] userIds, String message) {
        for (String userId : userIds) {
            Session session = sessionPool.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    logger.info("【websocket消息】 单点消息:" + message);
                    session.getAsyncRemote().sendText(message);
                } catch (Exception e) {
                    e.fillInStackTrace();
                }
            }
        }

    }

    /**
     * 讯飞星火请求chat聊天
     * @param sparkParam
     */
    public void getSparkApiChat(SparkParamDto sparkParam){
        try {
            // 构建鉴权url
            String authUrl = getAuthUrl(
                    SparkApiConfig.getHostUrl1(),
                    SparkApiConfig.getApiKey1(),
                    SparkApiConfig.getApiSecret1());
            OkHttpClient client = new OkHttpClient.Builder().build();
            String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
            Request request = new Request.Builder().url(url).build();
            String body = getSparkJsonSocket(SparkApiConfig.getAppId1(),sparkParam);

            StringBuilder builderSb =new StringBuilder();
            CompletableFuture<String> messageReceived = new CompletableFuture<>();

            WebSocket webSocket = client.newWebSocket(request, new WebSocketListener(){

                @Override
                public void onOpen(WebSocket webSocket, Response response) {
                    webSocket.send(body);
                }
                @Override
                public void onMessage(WebSocket webSocket, String res) {
                    JSONObject obj = JSON.parseObject(res);
                    String str= obj.getJSONObject("payload").getJSONObject("choices").getJSONArray("text").getJSONObject(0).getString("content");
                    builderSb.append(str);
                     sendOneMessage(sparkParam.getUserId(),str);
                    if(obj.getJSONObject("header").getLong("status")==2){
                        webSocket.close(1000, "Closing WebSocket connection");
                        messageReceived.complete(res); // 将收到的消息传递给 CompletableFuture
                    }
                }
            });

            String resItem = messageReceived.get(30, TimeUnit.SECONDS);// 阻塞等待消息返回
            webSocket.close(1000, "Closing WebSocket connection");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}

